import axios from 'axios'

const BASE_URL = window.baseURL || '/'
const TIMEOUT = 30 * 1000 // 请求超时时间

/*
*  用于判断后台返回状态，反馈给客户端
* */
const ajax = (config) => new Promise((resolve, reject) => axios({
  baseURL: BASE_URL,
  timeout: TIMEOUT, ...config,
  error: reject
}).then(resolve).catch(reject))

function service(config, option) {
  const {showError} = Object.assign({showError: true}, option)
  let rejectFun
  const ajaxPromise = new Promise(async function (resolve, reject) {
    rejectFun = reject
    try {
      const {status, data} = await ajax(config)
      if (status === 200) { // 系统状态
        const {code, msg} = data
        if (code !== 200) { // api 状态()
          const error = new Error(msg)
          error.name = code
          switch (code) {
            case 801:
              error.message = msg || '查无数据'
              break
            case 401:
              error.message = msg || '数据出错'
              break
            default:
              error.code = null
              error.message = data
              break
          }
          throw error
        }
        resolve(data)
      } else {
        throw new Error(status)
      }
    } catch (e) {
      let {name, message} = e

      if ([401, 801].includes(name)) {

      } else if (name && name !== 'Error' && message) {
        Message.error(message)
      } else {
        if (message.includes && message.includes('timeout')) {
          message = '连接超时'
        } else if (message.includes && message.includes('Network Error')) {
          e.message = message = '网络错误'
        } else {
          message = '连接异常'
        }
        showError && Message.error(message)
      }
      rejectFun(e)
    }
  })
  ajaxPromise.reject = rejectFun
  return ajaxPromise
}

export default service
